/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.foxline.clinicplus.manager;

import br.com.foxline.clinicplus.entity.*;
import br.com.foxline.clinicplus.enums.*;
import br.com.foxline.clinicplus.service.*;
import br.com.foxline.clinicplus.util.Caracter;
import br.com.foxline.clinicplus.util.Msg;
import java.io.Serializable;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import org.apache.commons.lang3.time.DateUtils;
import org.primefaces.context.RequestContext;
import org.primefaces.event.SelectEvent;
import org.primefaces.event.TabChangeEvent;
import org.primefaces.model.DefaultScheduleEvent;
import org.primefaces.model.LazyScheduleModel;
import org.primefaces.model.ScheduleModel;

/**
 *
 * @author roniere
 */
@ManagedBean
@ViewScoped
public class ManagerAtendimento implements Serializable {

    @EJB
    private DiaryService diaryService;
    @EJB
    private CustomerService customerService;
    @EJB
    private WaitingLineService waitingLineService;
    @EJB
    private DoctorService doctorService;
    @EJB
    private UnattendedService unattendedService;
    @EJB
    private IncomeService incomeService;
    @EJB
    private ProcedureService procedureService;
    @EJB
    private AnnexService annexService;
    @EJB
    private SystemUserService systemUserService;
    @EJB
    private OperatorService operatorService;
    @EJB
    private CityService cityService;
    @EJB
    private AppraisalService appraisalService;
    @EJB
    private RecordsService recordsService;
    //ATENDIMENTO PESQUISA/CADASTRO CUSTOMER
    private Customer customerpesquisar;
    private List<Customer> customers;
    //ATENDIMENTO PERFIL
    private Customer customer;
    private Address address;
    private Operator operator;
    private List<Diary> diarysRecents;
    //ATENDIMENTO PROCEDIMENTO
    private Operator operatorDiary;
    private List<Operator> operators;
    private Diary diary;
    private Procedure procedure;
    private Procedure procedureSearch;
    private Doctor doctor;
    private Doctor doctorPesquisar;
    private Doctor doctorRequest;
    private List<Doctor> doctors;
    private List<Procedure> procedures;
    private Income income;
    private BigDecimal discount;
    private List<Diary> diarysDisp;
    private List<Diary> diarysSelected;
    private List<Records> recordses;
    private String msg;
    private ScheduleModel eventModel;
    private boolean atendimento;
    private String dateString;
    private Date date;
    private boolean retorno;
    private Diary diaryrecord;
    private Date from;
    private boolean collapsed = true;
    private boolean showAll = true;
    private boolean showAnamnese = true;
    private boolean showExameFisico = true;
    private boolean showDiagnostico = true;
    private boolean showReceituario = true;
    private boolean showEvolucao = true;
    private boolean showAnexos = true;

    @PostConstruct
    public void init() {
        Map<String, String> params = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();



        if (params.get("step") != null) {
            if (params.get("step").equals("1")) {
                this.customerpesquisar = new Customer();
            } else if (params.get("step").equals("2") && params.get("customer") != null) {

                this.customer = customerService.find((Long.parseLong(params.get("customer"))));
                this.address = this.customer.getAddress();
                this.operator = this.customer.getOperator();
                this.recordses = recordsService.getHistoryRecords(this.customer);
                this.diarysRecents = diaryService.findDiaryCustomer(this.customer, "desc");
                existAppraisal();

            } else if (params.get("step").equals("3") && (params.get("customer") != null || params.get("diary") != null)) {
                if (params.get("diary") != null) {
                    this.diary = diaryService.find(Long.parseLong(params.get("diary")));
                    if (this.diary != null && this.diary.getStartTime() != null) {
                        this.from = this.diary.getStartTime();
                    }
                    if (params.get("retorno") != null) {
                        this.diary.setId(null);
                        this.diary.setRetornoDiary(diary);
                        retorno = params.get("retorno") != null ? true : false;
                        this.diary.setRetorno(atendimento);
                        this.diary.setDiarySituation(DiarySituation.SCHEDULED);
                        this.diary.setCreateAt(null);
                        this.diary.setSystemUser(null);
                        this.diary.setUpdateAt(null);
                        this.diary.setSystemUserUpdate(null);
                        this.diary.setRecords(null);
                        this.diary.setDateConsultation(null);
                    }

                    this.customer = this.diary.getCustomer();
                    this.procedure = this.diary.getProcedure();
                    this.operatorDiary = this.diary.getOperator();

                    if (params.get("retorno") == null) {
                        this.income = this.incomeService.diaryByIncome(diary);
                    }
                    if (this.income == null) {
                        this.income = new Income();
                        loadIncome();
                    }
                    this.doctor = this.diary.getDoctor();
                    this.doctorRequest = this.diary.getDoctorRequest();
                } else {
                    this.diary = new Diary();

                    this.diary.setDiarySituation(DiarySituation.SCHEDULED);
                    this.income = new Income();
                    this.income.setCreateAt(new Date());
                }

                if (params.get("customer") != null) {
                    this.customer = customerService.find((Long.parseLong(params.get("customer"))));
                }
                if (this.customer.getOperator() != null && this.operatorDiary == null) {
                    this.operatorDiary = this.customer.getOperator();
                }
                this.procedureSearch = new Procedure();
                this.operators = operatorService.findAll();
                this.doctorPesquisar = new Doctor();
                initSchedule();

                this.recordses = recordsService.getHistoryRecords(this.customer);
                this.diarysRecents = diaryService.findDiaryCustomer(this.customer, "desc");
                existAppraisal();
                if (params.get("atendimento") != null) {
                    atendimento = true;
                }

                if (params.get("date") != null && !params.get("date").isEmpty()
                        && !params.get("date").equals("null")) {
                    dateString = params.get("date");
                    SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
                    try {
                        dateString = dateString.replace("+", " ");
                        this.diary.setStartTime(sdf.parse(dateString));
                        onDateSelect(null);

                    } catch (ParseException ex) {
                        ex.printStackTrace();
                        Logger.getLogger(ManagerAtendimento.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        }

        this.diarysSelected = new ArrayList<Diary>();
    }

    public boolean isRetorno() {
        return retorno;
    }

    public void setRetorno(boolean retorno) {
        this.retorno = retorno;
    }

    public boolean getDoctorByLogin() {
        String user = FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal().getName();
        doctor = systemUserService.getDoctorByLogin(user);
        if (doctor == null) {
            return false;
        } else {
            return true;
        }
    }

    public void searchCustomer() {
        customerpesquisar.setCpf(Caracter.removecaracter(customerpesquisar.getCpf()));
        customers = customerService.findCustomer(customerpesquisar);
    }

    /**
     * Retorna a idade do paciente
     *
     * @return
     */
    public int getAge() {
        int idade = 0;
        if (customer.getDateBirth() != null) {
            Calendar c = new GregorianCalendar();
            Calendar dateBirth = new GregorianCalendar();
            dateBirth.setTime(customer.getDateBirth());

            idade = c.get(Calendar.YEAR) - dateBirth.get(Calendar.YEAR);

            dateBirth.add(Calendar.YEAR, idade);

            if (c.before(dateBirth)) {
                idade--;
            }
        }
        return idade;

    }

    public void listProcedure() {
        if (operatorDiary == null
                || (operatorDiary != null && (operatorDiary.getName().equalsIgnoreCase("sus")
                || operatorDiary.getName().equalsIgnoreCase("cortesia")))) {
            procedures = procedureService.findProcedure(procedureSearch, true);
        } else {
            procedures = procedureService.findProcedure(procedureSearch, operator);
        }
    }

    public void listDoctor() {
        doctors = doctorService.findDoctor(doctorPesquisar);
    }

    public void clearOperator() {
        operatorDiary = null;
        loadIncome();
    }

    public void clearProcedure() {
        procedure = null;
        loadIncome();
    }

    public void clearDoctor() {
        doctor = null;
        initSchedule();
    }

    public void clearDoctorRequest() {
        doctorRequest = null;
    }

    public List<SelectItem> selectPaymentType() {
        List<SelectItem> paymentTypes = new ArrayList<SelectItem>();
        for (PaymentType ms : PaymentType.values()) {
            paymentTypes.add(new SelectItem(ms, ms.getName()));
        }
        return paymentTypes;
    }

    public void calcDiscount() {
        income.setTotalAmount(income.getAmount());
        income.setAmountPaid(income.getAmount());

        if ((income.getDiscount() != null)
                && (!income.getDiscount().equals(BigDecimal.ZERO))) {
            income.setTotalAmount(income.getAmount().subtract(income.getDiscount()));
            income.setAmountPaid(income.getTotalAmount());
            discount = BigDecimal.ZERO;
        }

    }

    public void calcDiscountPorce() {
        if (discount == null) {
            discount = BigDecimal.ZERO;
            return;
        }
        if (discount != null && discount.compareTo(BigDecimal.ZERO) == 0) {
            if ((income.getDiscount() == null)
                    || (income.getDiscount().compareTo(BigDecimal.ZERO) == 0)) {

                income.setTotalAmount(income.getAmount());
                income.setAmountPaid(income.getAmount());
            }
            return;
        }
        if (income.getAmount() != null) {
            income.setTotalAmount(income.getAmount());
            income.setAmountPaid(income.getAmount());
            if (discount != null) {
                income.setTotalAmount(income.getAmount().subtract(income.getAmount().
                        multiply(discount)));
            }
            income.setAmountPaid(income.getTotalAmount());

            income.setDiscount(BigDecimal.ZERO);
        }
    }

    public void clearIncome() {
        income = null;
    }

    public List<SelectItem> selectTypeDiary() {
        List<SelectItem> diarySituation = new ArrayList<SelectItem>();
        for (DiarySituation ms : DiarySituation.values()) {
            diarySituation.add(new SelectItem(ms, ms + ""));
        }
        if (diary != null && diary.getId() != null && !verifyAdmin()) {
            List<SelectItem> removeList = new ArrayList<SelectItem>();
            for (SelectItem selectItem : diarySituation) {
                if (selectItem.getValue() == DiarySituation.CANCEL) {
                    removeList.add(selectItem);
                }
            }
            diarySituation.removeAll(removeList);
        }
        return diarySituation;
    }

    public boolean verifyAdmin() {
        return systemUserService.verifyAdmin();
    }
// ======================================================

    public Customer getCustomerpesquisar() {
        return customerpesquisar;
    }

    public void setCustomerpesquisar(Customer customerpesquisar) {
        this.customerpesquisar = customerpesquisar;
    }

    public List<Customer> getCustomers() {
        return customers;
    }

    public void setCustomers(List<Customer> customers) {
        this.customers = customers;
    }

    public Customer getCustomer() {
        return customer;
    }

    public void setCustomer(Customer customer) {
        this.customer = customer;
    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    public Operator getOperator() {
        return operator;
    }

    public void setOperator(Operator operator) {
        this.operator = operator;
    }

    public Diary getDiary() {
        return diary;
    }

    public void setDiary(Diary diary) {
        this.diary = diary;
    }

    public Doctor getDoctor() {
        return doctor;
    }

    public void setDoctor(Doctor doctor) {
        this.doctor = doctor;
    }

    public Doctor getDoctorRequest() {
        return doctorRequest;
    }

    public void setDoctorRequest(Doctor doctorRequest) {
        this.doctorRequest = doctorRequest;
    }

    public Operator getOperatorDiary() {
        return operatorDiary;
    }

    public void setOperatorDiary(Operator operatorDiary) {
        this.operatorDiary = operatorDiary;
    }

    public Procedure getProcedure() {
        return procedure;
    }

    public void setProcedure(Procedure procedure) {
        this.procedure = procedure;
    }

    public List<Operator> getOperators() {
        return operators;
    }

    public void setOperators(List<Operator> operators) {
        this.operators = operators;
    }

    public Procedure getProcedureSearch() {
        return procedureSearch;
    }

    public void setProcedureSearch(Procedure procedureSearch) {
        this.procedureSearch = procedureSearch;
    }

    public List<Procedure> getProcedures() {
        return procedures;
    }

    public void setProcedures(List<Procedure> procedures) {
        this.procedures = procedures;
    }

    public Doctor getDoctorPesquisar() {
        return doctorPesquisar;
    }

    public void setDoctorPesquisar(Doctor doctorPesquisar) {
        this.doctorPesquisar = doctorPesquisar;
    }

    public List<Doctor> getDoctors() {
        return doctors;
    }

    public void setDoctors(List<Doctor> doctors) {
        this.doctors = doctors;
    }

    public Income getIncome() {
        return income;
    }

    public void setIncome(Income income) {
        this.income = income;
    }

    public BigDecimal getDiscount() {
        return discount;
    }

    public void setDiscount(BigDecimal discount) {
        this.discount = discount;
    }

    public List<Diary> getDiarysDisp() {
        return diarysDisp;
    }

    public void setDiarysDisp(List<Diary> diarysDisp) {
        this.diarysDisp = diarysDisp;
    }

    public List<Diary> getDiarysSelected() {
        return diarysSelected;
    }

    public void setDiarysSelected(List<Diary> diarysSelected) {
        this.diarysSelected = diarysSelected;
    }

    public List<Records> getRecordses() {
        return recordses;
    }

    public void setRecordses(List<Records> recordses) {
        this.recordses = recordses;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public List<Diary> getDiarysRecents() {
        return diarysRecents;
    }

    public void setDiarysRecents(List<Diary> diarysRecents) {
        this.diarysRecents = diarysRecents;
    }

    public ScheduleModel getEventModel() {
        return eventModel;
    }

    public void setEventModel(ScheduleModel eventModel) {
        this.eventModel = eventModel;
    }

    public boolean isAtendimento() {
        return atendimento;
    }

    public void setAtendimento(boolean atendimento) {
        this.atendimento = atendimento;
    }

    // SALVAR
    public void salvar() {
        try {

            boolean required = false;
            if (operatorDiary == null || operatorDiary.getId() == null) {
                Msg.messagemError("Convênio é obrigatório");
                required = true;
            } else {
                diary.setOperator(operatorDiary);
            }

            if (procedure == null || procedure.getId() == null) {
                Msg.messagemError("Procedimento é obrigatório");
                required = true;
            } else {
                diary.setProcedure(procedure);
            }
            if (doctor == null || doctor.getId() == null) {
                Msg.messagemError("Médico Responsável é obrigatório");
                required = true;
            } else {
                diary.setDoctor(doctor);
            }

            if (customer != null && customer.getId() == null) {
                Msg.messagemError("Selecione um Paciente");
                return;
            } else {
                diary.setCustomer(customer);
            }

            if (required) {
                return;
            }

            if (doctorRequest != null && (doctorRequest.getId() != null)) {
                diary.setDoctorRequest(doctorRequest);
            } else {
                diary.setDoctorRequest(null);
            }

            if (retorno || (diary.getRetorno() != null && diary.getRetorno())) {
                diary.setRetorno(true);
            } else {
                diary.setRetorno(false);
            }

            diary.setStatus(true);
            diary.setCancel(false);

            Calendar start = new GregorianCalendar();
            Calendar end = new GregorianCalendar();
            Calendar c = new GregorianCalendar();

            start.setTime(diary.getStartTime());
            end.setTime(diary.getEndTime());

            c.setTime(from);
            start.set(GregorianCalendar.HOUR_OF_DAY, c.get(GregorianCalendar.HOUR_OF_DAY));
            start.set(GregorianCalendar.MINUTE, c.get(GregorianCalendar.MINUTE));

            end.set(GregorianCalendar.DAY_OF_MONTH, start.get(GregorianCalendar.DAY_OF_MONTH));
            end.set(GregorianCalendar.MONTH, start.get(GregorianCalendar.MONTH));
            end.set(GregorianCalendar.YEAR, start.get(GregorianCalendar.YEAR));

            this.diary.setStartTime(start.getTime());
            this.diary.setEndTime(end.getTime());

            if (diary.getId() == null) {
                diary.setSystemUser(systemUserService.getCurrentUser());
                diary.setDateConsultation(new Date());
                diary.setCreateAt(new Date());
                diaryService.save(diary);
            } else {
                diary.setSystemUserUpdate(systemUserService.getCurrentUser());
                diary.setUpdateAt(new Date());
                diaryService.update(diary);
            }

            if (diary.getId() != null && incomeService.diaryByIncome(diary) != null) {
                Income i = incomeService.diaryByIncome(diary);
                //SALVAR INCOME
            }

            //LISTA DE ESPERA
            if (this.diary.getDiarySituation() == DiarySituation.CALL_WAITING) {
                if (!this.diary.getRetorno()) {

                    if ((income.getAmount() == null || income.getAmount().compareTo(BigDecimal.ZERO) == 0
                            || (income.getAmountPaid() == null
                            || (income.getAmountPaid().compareTo(BigDecimal.ZERO) == 0
                            && (income.getDiscount() != null && income.getDiscount().compareTo(income.getAmount()) == -1))))
                            && diary != null && diary.getId() != null
                            && diary.getOperator() != null
                            && diary.getOperator().getId() != null
                            && !(diary.getOperator().getName().equalsIgnoreCase("SUS")
                            || diary.getOperator().getName().equalsIgnoreCase("cortesia"))) {

                        Msg.messagemWarn("Valor pago não pode ser zero ou vazio");
                        return;

                    } else {
                        saveIncome();
                    }
                }
                WaitingLine waitingLine;
                if (this.diary != null && waitingLineService.getWaitingLineForDiary(this.diary.getId()) == null) {
                    waitingLine = new WaitingLine();
                    waitingLine.setDiary(this.diary);
                    waitingLine.setInitial(new Date());
                    waitingLine.setStatus(true);
                    waitingLineService.save(waitingLine);
                }
            }

            //LAUDO
            if (this.diary.getDiarySituation() != null && this.diary.getDiarySituation() == DiarySituation.CALL_ENDED
                    && procedure != null && procedure.getTypeProcedure() == TypeProcedure.EXAME && procedure.getAppraisal()) {

                Appraisal appraisal = new Appraisal();
                appraisal.setCustomer(diary.getCustomer());
                appraisal.setCreatAt(new Date());
                appraisal.setDiary(diary);
                appraisal.setSystemUser(systemUserService.getCurrentUser());
                appraisal.setSituationAppraisal(SituationAppraisal.WAITING);
                appraisalService.save(appraisal);

            }

            //INCOME QUANDO CANCELAR
            if (this.diary.getDiarySituation() == DiarySituation.CANCEL) {

                if (incomeService.diaryByIncome(diary) != null) {
                    Income i = incomeService.diaryByIncome(diary);
                    diary.setIncome(null);
                    diary.setSystemUserUpdate(systemUserService.getCurrentUser());
                    diary.setUpdateAt(new Date());
                    diaryService.update(diary);
                    incomeService.delete(i);
                }

            }

        } catch (Exception e) {
            e.printStackTrace();
            Msg.messagemError("Ocorreu um Erro !");
            return;
        }

        Msg.messagemInfoRedirect(Msg.SuccessFull, "atendimentoprocedimento.xhtml?step=3&diary=" + this.diary.getId());
    }

    public void loadIncome() {
        if (procedure != null) {
            income = new Income();
            income.setDoctor(doctor);
            income.setCreateAt(new Date());
            income.setProcedure(procedure);
            income.setAmount(procedureService.getValueProcedureOperator(procedure, operatorDiary));
            income.setDiscount(BigDecimal.ZERO);
            income.setTotalAmount(income.getAmount());
            income.setAmountPaid(income.getAmount());
        }

        initSchedule();

    }

    public void saveIncome() {

        income.setDoctor(doctor);
        income.setProcedure(procedure);

        if (income.getId() == null) {
            income.setCreateAt(new Date());
            income.setSystemUser(systemUserService.getCurrentUser());
            income.setTypeIncome(TypeIncome.C);
            income.setDiary(diary);
            incomeService.save(income);

            diary.setIncome(income);
            diary.setSystemUserUpdate(systemUserService.getCurrentUser());
            diary.setUpdateAt(new Date());
            diaryService.update(diary);
            income = incomeService.find(income.getId());
        } else {
            incomeService.update(income);
            income = incomeService.find(income.getId());
        }
    }

    public void verifyOtherDiary() {
        diarysDisp = diaryService.getDiaryCustomerForDate(customer, DateUtils.addHours(diary.getStartTime(), -24), DateUtils.addHours(diary.getStartTime(), 24));
        diarysSelected.add(diary);
    }

    public void diaryReport() {
        diaryService.reportsDiaryExame(diary, diarysSelected);
    }

    public void diaryPorRecord(Long id) {
        if (id != null) {
            diaryrecord = recordsService.getDiaryRecords(id);
        }
    }

    public boolean verificaCadastroIncompleto() {
        boolean incompleto = false;
        if (this.customer.getCpf() == null || this.customer.getCpf().isEmpty()) {
            incompleto = true;
        }
        if (this.customer.getDateBirth() == null) {
            incompleto = true;
        }
        if (this.customer.getPhone() == null || this.customer.getCellular() == null) {
            incompleto = true;
        }
        if (this.customer.getAnnex() == null) {
            incompleto = true;
        }
        if (this.customer.getAddress() == null) {
            incompleto = true;
        } else {
            if (this.customer.getAddress().getPublicPark() == null || this.customer.getAddress().getPublicPark().isEmpty()) {
                incompleto = true;
            }
            if (this.customer.getAddress().getNeighborhood() == null || this.customer.getAddress().getNeighborhood().isEmpty()) {
                incompleto = true;
            }
            if (this.customer.getAddress().getCity() == null) {
                incompleto = true;
            }
        }
        return incompleto;
    }

    public String existAppraisal() {
        msg = "";
        List<Appraisal> lst = appraisalService.searchAppraisal(null, null, null, SituationAppraisal.FINISHED, null, null, customer);
        if (lst != null && !lst.isEmpty()) {
            for (Appraisal appraisal : lst) {
                msg += "<li>";
                msg += "<span class=\"ui-messages-warn-summary\">";
                msg += "Laudo nº <a href=\"createAppraisal.xhtml?appraisalEdit=" + appraisal.getId() + "\">"
                        + appraisal.getId() + "</a> do " + appraisal.getDiary().getProcedure().getName()
                        + " está disponível ";
                msg += "</span>";
                msg += "</li>";
            }
        } else {
            msg = null;
        }
        return msg;
    }

    public void initSchedule() {

        this.eventModel = new LazyScheduleModel() {

            @Override
            public void loadEvents(Date start, Date end) {
                clear();
                loadDiary(start, end);
            }
        };

        RequestContext context = RequestContext.getCurrentInstance();
        context.execute("myschedule.update();");
        context.update(":diaryForm:tabView:tba2");
    }

    private void loadDiary(Date dateInitial, Date dateFinal) {
        System.err.println("load");
        DefaultScheduleEvent eventObj;
        List<Diary> diarys = new ArrayList<Diary>();

        if ((procedure != null && procedure.getId() != null) && doctor == null) {
            diarys = diaryService.getDiaryForProcedure(procedure, dateInitial, dateFinal);
        } else if (doctor != null && doctor.getId() != null) {
            diarys = diaryService.getDiaryForDoctor(doctor, dateInitial, dateFinal);
        }
        for (Diary d : diarys) {
            String title = d.getCustomer().getName() + " - " + (d.getRetorno() != null ? (d.getRetorno() ? "RETORNO - " : "") : "")
                    + (d.getProcedure() == null ? "" + d.getDoctor().getName() : d.getProcedure().getName());
            eventObj = new DefaultScheduleEvent(title, d.getStartTime(), d.getEndTime(), d);
            if (d.getDiarySituation() != null) {
                eventObj.setStyleClass(d.getDiarySituation().toString().toLowerCase().replace(" ", "_"));

                if (d.getStatus() == false) {
                    eventObj.setStyleClass(DiarySituation.CALL_ENDED.toString().toLowerCase().replace(" ", "_"));
                }

            }
            eventModel.addEvent(eventObj);
        }

        for (Unattended unattended : unattendedService.findUnattended(doctor)) {
            eventObj = new DefaultScheduleEvent(doctor.getName() + " - " + unattended.getDescription(),
                    unattended.getStartTime(), unattended.getEndTime(), unattended);
            eventModel.addEvent(eventObj);

        }

    }

    public void onDateSelect(SelectEvent event) {
        Calendar c = new GregorianCalendar();

        if (event != null) {
            Date to = (Date) event.getObject();
            c.setTime(to);
        } else {
            c.setTime(this.diary.getStartTime());
        }

        this.diary.setStartTime(c.getTime());
        from = this.diary.getStartTime();
        c.add(GregorianCalendar.MINUTE, 20);

        this.diary.setEndTime(c.getTime());
    }

    public void onDateSelectFrom(SelectEvent event) {
        Calendar c = new GregorianCalendar();

        Calendar aux = new GregorianCalendar();
        aux.setTime(this.diary.getStartTime());

        if (event != null) {
            Date to = (Date) event.getObject();
            c.setTime(to);
        } else {
            c.setTime(this.from);
        }

        aux.set(GregorianCalendar.HOUR_OF_DAY, c.get(GregorianCalendar.HOUR_OF_DAY));
        aux.set(GregorianCalendar.MINUTE, c.get(GregorianCalendar.MINUTE));

        this.diary.setStartTime(aux.getTime());
        aux.add(GregorianCalendar.MINUTE, 20);
        this.diary.setEndTime(aux.getTime());

    }

    public void onTabChange(TabChangeEvent event) {
        System.err.println(event.getTab().getId());
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    public String getDateString() {
        return dateString;
    }

    public void setDateString(String dateString) {
        this.dateString = dateString;
    }

    public Diary getDiaryrecord() {
        return diaryrecord;
    }

    public void setDiaryrecord(Diary diaryrecord) {
        this.diaryrecord = diaryrecord;
    }

    public Date getFrom() {
        return from;
    }

    public void setFrom(Date from) {
        this.from = from;
    }

    public boolean isShowAnamnese() {
        return showAnamnese;
    }

    public void setShowAnamnese(boolean showAnamnese) {
        this.showAnamnese = showAnamnese;
    }

    public boolean isShowAnexos() {
        return showAnexos;
    }

    public void setShowAnexos(boolean showAnexos) {
        this.showAnexos = showAnexos;
    }

    public boolean isShowDiagnostico() {
        return showDiagnostico;
    }

    public void setShowDiagnostico(boolean showDiagnostico) {
        this.showDiagnostico = showDiagnostico;
    }

    public boolean isShowExameFisico() {
        return showExameFisico;
    }

    public void setShowExameFisico(boolean showExameFisico) {
        this.showExameFisico = showExameFisico;
    }

    public boolean isShowReceituario() {
        return showReceituario;
    }

    public void setShowReceituario(boolean showReceituario) {
        this.showReceituario = showReceituario;
    }

    public boolean isShowEvolucao() {
        return showEvolucao;
    }

    public void setShowEvolucao(boolean showEvolucao) {
        this.showEvolucao = showEvolucao;
    }

    public boolean isShowAll() {
        return showAll;
    }

    public void setShowAll(boolean showAll) {
        this.showAll = showAll;
    }

    public void todosFiltros() {

        showAnamnese = showAll;
        showAnexos = showAll;
        showDiagnostico = showAll;
        showEvolucao = showAll;
        showExameFisico = showAll;
        showReceituario = showAll;

    }

    public void disableShowAll() {

        if (showAnamnese
                && showAnexos
                && showDiagnostico
                && showEvolucao
                && showExameFisico
                && showReceituario) {
            showAll = true;
        }else{
            showAll = false;
        }

        collapsed = false;
    }

    public boolean isCollapsed() {
        return collapsed;
    }

    public void setCollapsed(boolean collapsed) {
        this.collapsed = collapsed;
    }
    
    
}
